< previous page page_451 next page >

Page 451
Declare Function lopen Lib "kernel32" Alias "_lopen" 
(ByVal lpPathName As String, ByVal iReadWrite As Long) As Long.
Visual Basic sees the function internally as lopen but knows from the Declare statement's Alias parameter to pass the call to the function named _lopen inside the kernel32 DLL. square.gif

Let me demonstrate the use of a Windows API function with the example mentioned earlier, rebooting the system. First, start a Standard EXE project, and add a new module by choosing Add Module from the Project menu. Next, go to the declarations section of the module, and enter the following Declare statement on a single line:
Declare Function ExitWindowsEx Lib "user32" (ByVal uFlags As Long,_
                 ByVal dwReserved As Long) As Long
note.gif Notice the underscore at the end of the first code line. Declare statements can be entered on multiple lines if the line continuation character (_) is used. square.gif

Notice that the Declare statement contains the name of the function (ExitWindowsEx), the name of the library (user32), and a list of parameters. After you enter the Declare statement, the ExitWindowsEx function is visible within Visual Basic and can be called from other code.
However, before calling the API function, you need to set up some valid values for the two parameters. The following constants are acceptable values for the first parameter, uFlags:
Public Const EWX_FORCE = 4
Public Const EWX_LOGOFF = 0
Public Const EWX_REBOOT = 2
Public Const EWX_SHUTDOWN = 1
If you look at the constants in the preceding list, you may notice that they roughly correspond to the choices available when you're closing Windows. Each constant passed to the uFlags parameter causes the function to behave differently, much like the Flags property of a CommonDialog control.
The second parameter, dwReserved, is typical of many Windows API functions. It is a reserved parameter not intended for general use, so you can just use 0 for its value.
note.gif Constants used with the Windows API are just like normal Visual Basic constants. For the sake of readability, I suggest placing these constants in the same module as the function declaration. square.gif

After you have entered the declaration statements and constants, calling the API function from code is easy. For example, place the following lines of Visual Basic code in the Form_Load procedure to reboot your computer:
Dim lRetVal As Long
lRetVal = ExitWindowsEx(EWX_REBOOT, 0)
Executing the preceding code causes Windows to attempt to shut down, prompting you to save open documents.

 
< previous page page_451 next page >